<template>
  <div class="inventoryEarly">
    <div class="publicSearch">
      <div class="searchBar" :style="{ height: isMoreSearch ? 'auto' : '' }">
        <el-button-group>
          <el-button @click="getFreezeData" size="mini" icon="el-icon-search"
            >查询</el-button
          >
          <el-button @click="clearSearchData" size="mini" icon="el-icon-refresh"
            >重置</el-button
          >
        </el-button-group>
        <div>
          <span>货主</span>
          <el-select
            v-model="searchData.organizationId"
            size="mini"
            filterable
            placeholder="请选择货主"
            clearable
          >
            <el-option
              v-for="item in organizations"
              :key="item.organizationId"
              :label="item.organizationName"
              :value="item.organizationId"
            >
            </el-option>
          </el-select>
        </div>
          <div>
          <span>超期状态</span>
          <el-select
            v-model="searchData.earlyState"
            size="mini"
            filterable
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div>
          <span>物料编码</span>
          <el-input
            v-model.trim="searchData.itemCode"
            size="mini"
            placeholder="物料编码"
            clearable
          ></el-input>
        </div>
           <div>
          <span>物料名称</span>
          <el-input
            v-model.trim="searchData.itemName"
            size="mini"
            placeholder="物料名称"
            clearable
          ></el-input>
        </div>
         <div>
          <span>货位</span>
          <el-input
            v-model.trim="searchData.cellCode"
            size="mini"
            placeholder="货位"
            clearable
          ></el-input>
        </div>
         <div>
          <span>批次号</span>
          <el-input
            v-model.trim="searchData.batchName"
            size="mini"
            placeholder="批次号"
            clearable
          ></el-input>
        </div>
        <div>
          <span>追踪号</span>
          <el-input
            v-model.trim="searchData.boxCode"
            size="mini"
            placeholder="追踪号"
            clearable
          ></el-input>
        </div>
        <!-- <div>
          <span>收货时间</span>
          <el-date-picker
            v-model="searchData.createTimeArr"
            size="mini"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div> -->
        
      </div>
      
      <span
        class="moreSearchBtn"
        :class="isMoreSearch ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
        @click="isMoreSearch = !isMoreSearch"
      ></span>
    </div>
    <div class="headerBtns">
      <el-button
        size="small"
        type="info"
        round
        icon="iconfont icon-xiazaimoban"
        @click="exportExcel"
      >导出表格</el-button>
    </div>

    <div class="tableBox">
      <el-table highlight-current-row :data="freezes" style="width: 100%">
        <el-table-column fixed="left" type="index" width="50">
        </el-table-column>
    
        <el-table-column
       
          show-overflow-tooltip
          prop="earlyState"
          label="超期状态"
          width="100"
        >
          <template slot-scope="scope">
            <div>
              <el-tag v-show="scope.row.earlyState === 0" type="success" 
                >正常</el-tag
              >
              <el-tag v-show="scope.row.earlyState === 1" type="warning">临近有效期</el-tag>
              <el-tag v-show="scope.row.earlyState === 2" type="danger"
                >超期</el-tag
              >
            
            </div>
          </template>
        </el-table-column>
        
        <el-table-column
         
          show-overflow-tooltip
          prop="itemCode"
          label="物料编码"
        >
        </el-table-column>
        <el-table-column
          
          show-overflow-tooltip
          prop="itemName"
          label="物料名称"
        >
        </el-table-column>
        <el-table-column
          
          show-overflow-tooltip
          prop="cellCode"
          label="货位"
        >
        </el-table-column>
        <el-table-column
         
          show-overflow-tooltip
          prop="batchName"
          label="批次号"
        >
        </el-table-column>
        <el-table-column
         
          show-overflow-tooltip
          prop="boxCode"
          label="追踪号"
        >
        </el-table-column>
        <el-table-column
         
          show-overflow-tooltip
          prop="quantity"
          label="数量"
        >
        </el-table-column>
        <!-- <el-table-column
         
          show-overflow-tooltip
          prop="acceptTime"
          label="收货时间"
        >
         <template slot-scope="scope">
            {{ scope.row.acceptTime != null ? scope.row.acceptTime.substr(0, 10) : '' }}
          </template>
         </el-table-column> -->
          <el-table-column
         
          show-overflow-tooltip
          prop="inDate"
          label="有效期(天)"
        >
         </el-table-column>
           <el-table-column
       
          show-overflow-tooltip
          prop="earlyDay"
          label="预警天数(天)"
        >
         </el-table-column>
           <el-table-column
         
          show-overflow-tooltip
          prop="shortEarlyDay"
          label="距离超期天数(天)"
        >
         </el-table-column>
      </el-table>
      <el-pagination
        style="text-align: right"
        class="pagination-bottom"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :page-sizes="[15, 30, 50, 100]"
        :current-page.sync="searchData.pageNum"
        :page-size="searchData.pageSize"
        layout="sizes, total, prev, pager, next, jumper"
        :total="searchData.total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "Freeze",
  data() {
    return {
      isMoreSearch: false,
      isMoreSearch2: false,
      options: [{
          value: 0,
          label: '正常'
        },
        {
          value: 1,
          label: '临近有效期'
        },
        {
          value: 2,
          label: '超期'
        }],
      searchData: {
        pageNum: 1,
        pageSize: 15,
        total: null,
        keyWords: "",
        insertType: 0,
        wareId: PF.getLocal("wareId", "number"),
        billNo: "",
        state: "",
        organizationId: -1,
        createTimeArr: [],
        startTime: "",
        endTime: "",
        freezeDescribe: "",
        earlyState : "",
        itemCode : "",
        itemName : "",
        cellCode : "",
        batchName : "",
        boxCode : ""
      },
      searchSelectInventory: {
        pageNum: 1,
        pageSize: 5,
        total: null,
        keyWords: "",
        wareId: PF.getLocal("wareId", "number"),
        organizationId: null,
      },

      wares: [],
      organizations: [],
      freezes: [],
      inventorys: [],
      multipleSelection: [],
      selectIds: [],
      freezeReasons: [],

      dialogNewVisible: false,
      dialogUpdateVisible: false,
      innerVisibleInventory: false,

      formLabelWidth: "120px",

      form: {
        freezeMaster: {
          wareId: PF.getLocal("wareId", "number"),
          wareName: PF.getLocal("wareName"),
          freezeDescribe: "",
          memo: "",
          organizationId: -1,
          organizationName: "",
        },
        freezeDetails: [],
      },
      rules: {
        freezeDescribe: [
          { required: true, message: "请输入冻结原因", trigger: "blur" },
        ],
        memo: [{ required: true, message: "请输入备注", trigger: "blur" }],
        organizationId: [
          { required: true, message: "请选择货主", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState(["reviewStates"]),
    isFreezeBtn() {
      if (this.multipleSelection.length <= 0) {
        return true;
      }
      let organizationId = this.multipleSelection[0].organizationId;
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (organizationId !== this.multipleSelection[i].organizationId) {
          return true;
        }
      }
      return false;
    },
  },
  methods: {
    //导出功能
    
     exportExcel(){
          if (this.searchData.createTimeArr.length > 0) {
         this.searchData.startTime = this.searchData.createTimeArr[0] + " 00:00:00";
          this.searchData.endTime = this.searchData.createTimeArr[1] + " 23:59:59";
        }
        let ip = localStorage.getItem("baseUrl");
        let token = PF.getLocal("token");
        let url = ip + "/inventorys/exportExcel?earlyState="+this.searchData.earlyState+ 
                "&itemCode="+this.searchData.itemCode
                +"&itemName="+this.searchData.itemName+
                "&cellCode="+this.searchData.cellCode+
                "&batchName="+this.searchData.batchName+
                "&boxCode="+this.searchData.boxCode+
                "&startTime="+this.searchData.startTime+
                "&endTime="+this.searchData.endTime+
                "&organizationId="+this.searchData.organizationId;
        var xhr = new XMLHttpRequest();
        xhr.open("get", url, true); // get、post都可
        xhr.responseType = "blob";  // 转换流
        xhr.setRequestHeader("access-token",token); // token键值对
        xhr.onload = function() {
          if (this.status == 200) {
            var blob = this.response;
            var a = document.createElement("a")
            var url = window.URL.createObjectURL(blob)
            a.href = url
            a.download = "有效期预警表.xlsx"  // 文件名
          }
          a.click()
          window.URL.revokeObjectURL(url)
        }
        xhr.send();
      },
    handleSizeChange(val) {
      this.searchData.pageSize = val;
      this.getFreezeData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getFreezeData();
    },
    handleCurrentChange2(val) {
      this.searchSelectInventory.pageNum = val;
      this.getInventoryData();
    },
    clearSearchData() {
      this.searchData.keyWords = "";
      this.searchData.createTimeArr = [];
      this.searchData.startTime = "";
      this.searchData.endTime = "";
      this.searchData.billNo = "";
      this.searchData.state = "";
      this.searchData.organizationId = -1;
      this.searchData.freezeDescribe = "";
      this.searchData.earlyState = "";
      this.searchData.itemName = "";
      this.searchData.itemCode = "";
      this.searchData.cellCode = "";
      this.searchData.batchName = "";
      this.searchData.boxCode ="";
    },
 
    getFreezeData() {
      let searchData = PF.JSON(this.searchData);
      if (searchData.createTimeArr.length > 0) {
        this.searchData.startTime = this.searchData.createTimeArr[0] + " 00:00:00";
          this.searchData.endTime = this.searchData.createTimeArr[1] + " 23:59:59";
      }
      IOT.getServerData("/inventorys/inventoryEarlyList", "get", searchData, (ret) => {
        if (ret.code === 200) {
            console.log("hahh1"+ret.rows)
          this.freezes = ret.rows;
          this.searchData.total = ret.total;
          this.searchData.pageNum = ret.pageNumber;
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    getWareData() {
      IOT.getServerData("/ware/infos/findSome", "get", {}, (ret) => {
        if (ret.code === 200) {
          this.wares = ret.rows;
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    getInventoryData() {
      IOT.getServerData(
        "/inventorys/list",
        "get",
        this.searchSelectInventory,
        (ret) => {
          if (ret.code === 200) {
            this.inventorys = ret.rows;
            this.searchSelectInventory.total = ret.total;
            this.searchSelectInventory.pageNum = ret.pageNumber;
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },
    resetForm(formName) {
      // 重置
      this.$refs[formName].resetFields();
    },
    handleClose(done) {
      this.resetForm("form.freezeMaster");
      this.dialogNewVisible = false;
    },
    showSelectInventoryModal() {
      if (!PF.isNull(this.form.freezeMaster.wareId)) {
        IOT.tips("未获取到仓库！", "error");
        return false;
      } else if (!PF.isNull(this.form.freezeMaster.organizationId)) {
        IOT.tips("请先选择货主！", "error");
        return false;
      }
      this.searchSelectInventory.wareId = this.form.freezeMaster.wareId;
      this.searchSelectInventory.organizationId =
        this.form.freezeMaster.organizationId;
      this.selectIds = [];
      for (let i = 0; i < this.form.freezeDetails.length; i++) {
        this.selectIds.push(this.form.freezeDetails[i].inventoryId);
      }
      this.getInventoryData();
      this.innerVisibleInventory = true;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    clickSelectInventory() {
      let list = PF.JSON(this.multipleSelection);
      this.form.freezeMaster.wareId = list[0].wareId;
      this.form.freezeMaster.wareName = list[0].wareName;
      this.form.freezeMaster.organizationId = list[0].organizationId;
      this.form.freezeMaster.organizationName = list[0].organizationName;

      let isRepeat = false;
      for (let i = 0; i < list.length; i++) {
        list[i].nowFreezeQuantity = list[i].freezeQuantity;
        list[i].freezeQuantity = 0;
        if (this.form.freezeDetails.length > 0) {
          if (
            this.selectIds.indexOf(list[i].inventoryId) === -1 &&
            list[i].organizationId === this.form.freezeDetails[0].organizationId
          ) {
            this.form.freezeDetails.push(list[i]);
          } else {
            isRepeat = true;
          }
        } else {
          if (this.selectIds.indexOf(list[i].inventoryId) === -1) {
            this.form.freezeDetails.push(list[i]);
          } else {
            isRepeat = true;
          }
        }
      }
      if (isRepeat) {
        IOT.tips("不能重复添加或添加非此货主！", "error");
      }
      this.innerVisibleInventory = false;
    },
    deleteDetail(index) {
      this.form.freezeDetails.splice(index, 1);
    },
    commitForm(formName, insertType) {
      let that = this;
      IOT.showOverlay("保存中，请稍等...");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = this.form;
          if (form.freezeDetails.length <= 0) {
            IOT.tips("未选择库存,请重新选择！", "error", 1000, () => {
              IOT.hideOverlay();
            });
            return false;
          }
          for (let i = 0; i < form.freezeDetails.length; i++) {
            if (form.freezeDetails[i].freezeQuantity === 0) {
              IOT.tips("数量不得为零,请重新输入！", "error", 1000, () => {
                IOT.hideOverlay();
              });
              return false;
            }
          }
          form.insertType = insertType;
          IOT.getServerData("/inventoryEarly/masters/insert", "post", form, (ret) => {
            IOT.hideOverlay();
            if (ret.code === 200) {
              IOT.tips("保存成功！", "success", 1000, () => {
                that.getFreezeData();

              });
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          });
          this.resetForm(formName);
          this.dialogNewVisible = false;
        } else {
          IOT.hideOverlay();
          console.error("error submit!!");
          return false;
        }
      });
    },
  },
  created() {
    this.getFreezeData();
    PF.getDataDictUdfData("freeze_reason", (rows) => {
      this.freezeReasons = rows;
    });
    this.getWareData();
    PF.getOrganizations((rows) => {
      this.organizations = rows;
    });
  },
  mounted() {},
};
</script>

<style scoped lang="less">
.inventoryEarly {
  input:focus {
    outline: none; // 如何把蓝色去掉？
    border: 1px solid #30b101; // 如何改成别的颜色？
  }
}
</style>
